package com.cfjjc.gz.common.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cfjjc.gz.common.consts.SystemConst;
import com.cfjjc.gz.common.dao.DefaultDAO;
import com.cfjjc.gz.common.exception.OTSException;
import com.cfjjc.gz.common.util.MD5;
import com.cfjjc.gz.funcpermission.vo.R_MENUVO;
import com.cfjjc.gz.funcpermission.vo.R_USR_ROLEVO;
import com.cfjjc.gz.usraccount.vo.A_USRVO;


/**
 * 
 * 说明：用户登录业务逻辑层对象
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class LoginService {
	
	private static final Logger logger = Logger.getLogger(LoginService.class);
	
	@Autowired
	private DefaultDAO dao;
	
	public LoginService() {
		super();
		logger.debug("************* loading LoginService *****************");
	}
	
	
	/**
	 * 用户登录处理逻辑
	 * 
	 * @param user
	 * @return 用户登录信息
	 * @param ip
	 * @return IP 地址
	 * @throws OTSException
	 */
	public A_USRVO doUserLogin(A_USRVO usr) throws OTSException {
/*		TcpConnector tcpConn = new TcpConnector(CacheTool.getNode(null, SystemConst.YES_CONST).getNode_ip(), SocketOptConst.AUTH_PORT);
		String pwd = ThreeDES.encrypt(usr.getPassword());
		String sendMsg = "serviceName=Auth" + SocketOptConst.SOCKET_SEPARATOR_COL + 
				"logID=" + usr.getLogin_name() + "-"+ usr.getAuth_mode() +"" 
				+ SocketOptConst.SOCKET_SEPARATOR_COL + "passwd=" + pwd +
				SocketOptConst.SOCKET_SEPARATOR_COL + "loginApp=WEB" +
				SocketOptConst.SOCKET_SEPARATOR_COL + "nodeID=" + 
				CacheTool.getNode(null, SystemConst.YES_CONST).getNode_code() 
				+SocketOptConst.SOCKET_SEPARATOR_COL;
		
		//String sendMsg = "serviceName=Auth" + "|logID=" + usr.getLogin_name() + "-"+ usr.getAuth_mode() +"" + "|passwd=" + pwd + "|loginApp=WEB" + "|nodeID=" + CacheTool.getNode(null, SystemConst.YES_CONST).getNode_code();

		logger.debug("明文：" + sendMsg);
		
		String str = "";
		int length = sendMsg.getBytes().length;
		str = String.format("%08d", length);
		sendMsg = str + sendMsg;
		tcpConn.write(sendMsg);
		String receiveMsg = tcpConn.read();
		tcpConn.close();
		if (StringUtil.isEmpty(receiveMsg)) {
			throw new OTSException("请求认证服务未返回信息！");
		}
		
		String[] strArray = receiveMsg.split(SocketOptConst.SOCKET_SEPARATOR_COL);
		
		String result_code = strArray[0].substring(strArray[0].indexOf("=")+1);
		if ("0000".equals(result_code)) {*/
			A_USRVO query = new A_USRVO();
			query.setLogin_name(usr.getLogin_name());
			
			logger.debug(query.getLogin_name());
			
			System.out.println("*********************"+query.getLogin_name());
			
			A_USRVO rs_usr = (A_USRVO) dao.queryObject(query, "A_USR"); 
			
			System.out.println("************明文：*********"+usr.getPassword());
			System.out.println("************明文：*********"+MD5.encodeByMD5(usr.getPassword()));
			
			logger.debug("明文：" + usr.getPassword());
			
			if(rs_usr==null||rs_usr.getStatic_pwd_md5()==null)
			{
				System.out.println("没有查到此用户");
				throw new OTSException("没有查到此用户");
			}
			
			if(MD5.compare(rs_usr.getStatic_pwd_md5(), usr.getPassword()))
			{
				
				return rs_usr;
			}
			else
			{
				throw new OTSException("密码错误");
				
			}
			
			
/*		} else {
			throw new OTSException( strArray[0].substring( strArray[0].indexOf("=")+1));
		}*/
	}
	
	
	
	// 获取用户的权限信息
	@SuppressWarnings("unchecked")
	public List<R_MENUVO> queryUserLimit(A_USRVO param) throws OTSException {
		// 查询用户的菜单 只是针对系统管理员的查询
		Map root = new HashMap();

		root.put("id", "0");
		root.put("text", "菜单列表");
		
		List menus = null;
		String login_name = param.getLogin_name();
		
		// 当登录用户是默认的管理员，则显示全部菜单
		if (SystemConst.DEFAULT_ADMIN.equals(login_name)) {
			R_MENUVO r_menu = new R_MENUVO();
			r_menu.setIs_enable(SystemConst.YES_CONST);
			menus = dao.queryList(r_menu, "R_MENU");

		} else {
 			R_USR_ROLEVO query = new R_USR_ROLEVO();
			query.setUsr_id(param.getUsr_id());
			query.setIs_enable(SystemConst.YES_CONST);
			menus = dao.queryList(query, "R_USR_ROLE", "queryMenu");  
		}
		List treeData = _formatTreeData(menus, root, 0, 0);
		if (treeData.size() > 0) {
			treeData = (List) (((Map) treeData.get(0)).get("children"));
		}

		return treeData;
	}
	
	
	
	/** 以下为set,get方法 */

	/**
	 * 将数据格式化为树型结构数据。树型结构数据格式如下： [{"id": "001", "'text": "系统管理","children":
	 * [{"id": "001002", "'text": "角色管理"},{"id": "001003", "'text": "用户管理"}]}]
	 * <p>
	 * 
	 * @param srcData
	 *            原始数据集合
	 * @param preMap
	 *            循环原始数据集合中的上次记录（相对应当前循环体中的记录），格式为Map对象形式
	 * @param preLevel
	 *            循环原始数据集合中的上次记录在树型结构中的级次
	 * @param begin
	 *            循环体从哪条记录开始的索引
	 * 
	 * @return 返回 格式化为树型结构的数据
	 */
	@SuppressWarnings("unchecked")
	private List _formatTreeData(List srcData, Map preMap, int preLevel,
			int begin) {

		List<Map> list = new ArrayList<Map>();
		list.add(preMap);

		for (int i = begin, len = srcData.size(); i < len; i++) {
			R_MENUVO node = (R_MENUVO) srcData.get(i);
			Map<String, Object> item = new HashMap<String, Object>();

			item.put("id", node.getMenu_code());
			item.put("text", node.getMenu_name());
			item.put("attributes", node);

			if (node.getMenu_level() == "1" || "0".equals(node.getIs_leaf())) {
				item.put("state", "closed");
			} else {
			}

			int curLevel = new Integer(node.getMenu_level());

			if (curLevel == (preLevel + 1)) {
				List child = (List) preMap.get("children");

				if (child != null && child.size() > 0) {
					child.addAll(_formatTreeData(srcData, item, curLevel, i + 1));

				} else {
					preMap.put("children",
							_formatTreeData(srcData, item, curLevel, i + 1));
				}

			} else if (curLevel <= preLevel) {
				break;
			}
		}

		return list;
	}

}
